#-- coding:UTF-8 --
import sys
import os
import cv2
import re
import logging
from configparser import ConfigParser
import redis

logging.disable(logging.DEBUG)      # 关闭debug日志的打印
logging.disable(logging.WARNING)    # 关闭warning日志的打印

sys.path.append(os.path.expanduser('~/Codes/PaddleOCR'))
from paddleocr import PaddleOCR

# 创建redis连接池
pool = redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 初始化redis中的各项数值
r.set('section','0')
r.set('A','0')
r.set('B','0')
r.set('gametime','00:00.0')


def im_show(image):
    plt.imshow(image)
    plt.show()
    
def show_txt(image, det_boxes_scores):
    bifen_txt = []
    for box, txt_score in det_boxes_scores[0]:
        x1, y1 = box[0]
        x1, y1 = int(x1), int(y1)
        x2, y2 = box[2]
        x2, y2 = int(x2), int(y2)
        color = (0, 255, 0)
        cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
        txt, score = txt_score
        txt = txt.replace(' ', '')
        match_jie = re.match(r"第\d+节", txt)
        match_obj = re.match(r"\d+:\d+", txt)
        if match_obj or match_jie:
            bifen_txt.append(txt)
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(image, txt,(x1-10, y1-10),font, 2, (255,0, 0), 3)
    im_show(image)
    return bifen_txt

def detect_txt(image, det_boxes_scores):
    bifen_txt = []
    for box, txt_score in det_boxes_scores[0]:
        x1, y1 = box[0]
        x1, y1 = int(x1), int(y1)
        x2, y2 = box[2]
        x2, y2 = int(x2), int(y2)
        txt, score = txt_score
        txt = txt.replace(' ', '')
        match_jie = re.match(r"第\d+节", txt)
        match_obj = re.match(r"\d+:\d+", txt)
        if match_obj or match_jie:
            bifen_txt.append(txt)
    if(len(bifen_txt) < 3):
        print("******** missing score ********\n")
        while(len(bifen_txt) < 3):
            bifen_txt.append("miss")
    
    # 构造消息报文
    # 如果返回miss，就不再构造报文
    if bifen_txt[2] != 'miss':  
 
        # 否则继续处理报文
        msg_txt = bifen_txt[0][1]    # 节号

        temp_txt = bifen_txt[1][:bifen_txt[1].find(':')]  # 主队比分
        temp_txt = temp_txt.rjust(3,'0')                  # 右侧对齐，左侧补0
        msg_txt = msg_txt + temp_txt                      # add主队比分

        temp_txt = bifen_txt[1][bifen_txt[1].find(':')+1:]  # 客队比分
        temp_txt = temp_txt.rjust(3,'0')                    # 右侧对齐，左侧补0
        msg_txt = msg_txt + temp_txt                      # add客队比分

        # temp_txt = bifen_txt[2][:bifen_txt[2].find(':')]  # 倒计时：分钟
        # msg_txt = msg_txt + temp_txt                      # 
        
        try:
            msg_txt = msg_txt + bifen_txt[2]
        except IndexError:
            print("IndexError")

        bifen_txt.append(msg_txt + '\n')

    return bifen_txt


ocr_engine = PaddleOCR()

#image_path = '/mnt/data/huangying/datas/比分大屏/现场比分大屏/上半场/live1.ts_imgs/03601.jpeg'
#image = cv2.imread(image_path)
#url = 'rtsp://192.168.8.162/live_stream'    # 拉相机
# url = 'rtmp://192.168.8.97/live'                    # 拉obs流
url = '/mnt/data/huangying/datas/from_zxm/2023-12-25_18_31_58赛前2.ts'
vid_capture = cv2.VideoCapture(url)

result_txt = open("result2.txt", 'w')

# 打开bifen.ini文件
# file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bifen.ini")
# cf = ConfigParser()
# cf.read('bifen.ini', encoding='utf-8')
# print(cf.sections())
# print(cf.options('bifen'))


frame_id = 0
sucess, frame = vid_capture.read()
recog_fps = 25
while sucess:
    frame_id += 1
    sucess, frame = vid_capture.read()
    if frame_id % recog_fps == 0:
        det_boxes_scores = ocr_engine.ocr(frame)
        #bifen_txt = show_txt(frame, det_boxes_score)
        bifen_txt = detect_txt(frame, det_boxes_scores)

        result_txt.write("frame:{}\n".format(frame_id))
        for bifen in bifen_txt:
            print(bifen)
            # result_txt.write("{}\n".format(bifen))
            # result_txt.flush()

        if bifen_txt[2] != 'miss':
            # 1. 写到bifen.ini文件中 
            '''
            cf.set("bifen","part",bifen_txt[3][0]) 
            cf.set('bifen','a_score',bifen_txt[3][1:4])
            cf.set('bifen','b_score',bifen_txt[3][4:7])
            cf.set('bifen','time',bifen_txt[3][7:])
            cf.set('bifen','msg_txt',bifen_txt[3])
            cf.write(open(file_path, 'w'))
            '''

            # 2. 写到redis中
            r.set('section',bifen_txt[3][0])
            r.set('A',bifen_txt[3][1:4])
            r.set('B',bifen_txt[3][4:7])
            r.set('gametime',bifen_txt[3][7:])


        
result_txt.close()
# close(file_path)
#boxes, txt_scores, _ = det_boxes_score

